<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="地区名称" prop="name">
        <el-input
            v-model="queryParams.name"
            placeholder="请输入地区名称"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['dictionaries:regions:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="info"
            plain
            icon="Sort"
            @click="toggleExpandAll"
        >展开/折叠</el-button>
      </el-col>
      <!--更新地区数据按钮-->
      <el-col :span="1.5">
        <el-button
            type="info"
            plain
            icon="Refresh"
            @click="confirmUpdateAll"
            v-hasPermi="['dictionaries:regions:edit']"
            style="background-color: #ffcccc; color: #000000;"
        >更新</el-button>
      </el-col>

      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
        v-if="refreshTable"
        v-loading="loading"
        :data="regionsList"
        row-key="id"
        lazy
        :load="load"
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
        @node-click="handleNodeClick"
    >
      <el-table-column label="地区名称" prop="name" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['dictionaries:regions:edit']">修改</el-button>
          <el-button link type="primary" icon="Plus" @click="handleAdd(scope.row)" v-hasPermi="['dictionaries:regions:add']">新增</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['dictionaries:regions:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改地区管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="regionsRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="地区名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入地区名称" />
        </el-form-item>
        <el-form-item label="父id" prop="parentId">
          <el-tree-select
              v-model="form.parentId"
              :data="regionsOptions"
              :props="{ value: 'id', label: 'name', children: 'children' }"
              value-key="id"
              placeholder="请选择父id"
              check-strictly
              :load="loadTreeSelect"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Regions">
import { listRegions, getRegions, delRegions, addRegions, updateRegions, getRegionsByParentId, listUpdatedRegions } from "@/api/dictionaries/regions";
import { ref, reactive, toRefs, nextTick } from 'vue';
import { getCurrentInstance } from 'vue';

const { proxy } = getCurrentInstance();

const regionsList = ref([]);
const regionsOptions = ref([{ id: "0", name: '顶级节点', children: [] }]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const title = ref("");
const isExpandAll = ref(false);
const refreshTable = ref(true);

const data = reactive({
  form: {},
  queryParams: {
    name: null,
    parentId: null
  },
  rules: {}
});

const { queryParams, form, rules } = toRefs(data);

/** 查询地区管理列表 */
function getList() {
  loading.value = true;
  listRegions(queryParams.value).then(response => {
    regionsList.value = proxy.handleTree(response.data, "id", "parentId");
    // 标记根节点是否有子节点
    regionsList.value.forEach(item => {
      item.hasChildren = true;
    });
    loading.value = false;
  });
}

// 更新所有地区数据
function handleUpdateAll() {
  listUpdatedRegions().then(response => {
    proxy.$modal.msgSuccess("更新成功");
    getList();
  });
}

/** 确认更新所有地区数据 */
function confirmUpdateAll() {
  proxy.$modal.confirm('是否确认更新所有地区数据？').then(function () {
    return handleUpdateAll();
  }).catch(() => { });
}

/** 查询地区管理下拉树结构 */
function getTreeselect() {
  listRegions().then(response => {
    regionsOptions.value = [];
    const data = { id: "0", name: '顶级节点', children: [] };
    data.children = proxy.handleTree(response.data, "id", "parentId");
    regionsOptions.value.push(data);
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    name: null,
    parentId: null
  };
  proxy.resetForm("regionsRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 新增按钮操作 */
function handleAdd(row) {
  reset();
  getTreeselect();
  if (row != null && row.id) {
    form.value.parentId = row.id;
  } else {
    form.value.parentId = "0";
  }
  open.value = true;
  title.value = "添加地区管理";
}

/** 展开/折叠操作 */
function toggleExpandAll() {
  refreshTable.value = false;
  isExpandAll.value = !isExpandAll.value;
  nextTick(() => {
    refreshTable.value = true;
  });
}

/** 处理节点点击事件，展开点击的节点及其子节点 */
function handleNodeClick(row, node, e) {
  node.expanded = true;
  if (row.children) {
    row.children.forEach(child => {
      const childNode = node.childNodes.find(n => n.data.id === child.id);
      if (childNode) {
        childNode.expanded = true;
      }
    });
  }
}

/** 修改按钮操作 */
async function handleUpdate(row) {
  reset();
  await getTreeselect();
  if (row != null) {
    form.value.parentId = row.parentId;
  }
  getRegions(row.id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改地区管理";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["regionsRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateRegions(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addRegions(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  proxy.$modal.confirm('是否确认删除地区管理编号为"' + row.id + '"的数据项？').then(function () {
    return delRegions(row.id);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

/** 懒加载数据 */
async function load(tree, treeNode, resolve) {
  try {
    const response = await getRegionsByParentId(tree.id);
    const children = response.data;
    children.forEach(item => {
      item.hasChildren = true;
    });
    resolve(children);
  } catch (error) {
    console.error('获取子节点数据失败', error);
    resolve([]);
  }
}

/** 懒加载 el-tree-select 数据 */
async function loadTreeSelect(node, resolve) {
  try {
    const response = await getRegionsByParentId(node.id);
    const children = response.data;
    children.forEach(item => {
      item.hasChildren = true;
    });
    resolve(children);
  } catch (error) {
    console.error('获取 el-tree-select 子节点数据失败', error);
    resolve([]);
  }
}

getList();
</script>
